package com.meihuayishu.backend.service.impl;

import com.meihuayishu.backend.dto.UserDTO;
import com.meihuayishu.backend.dto.UserDivinationSettingsDTO;
import com.meihuayishu.backend.dto.UserLoginDTO;
import com.meihuayishu.backend.dto.UserRegistrationDTO;
import com.meihuayishu.backend.entity.User;
import com.meihuayishu.backend.repository.FeedbackRepository;
import com.meihuayishu.backend.repository.UserRepository;
import com.meihuayishu.backend.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import jakarta.persistence.EntityNotFoundException;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final FeedbackRepository feedbackRepository;
    
    @Override
    public UserDTO register(UserRegistrationDTO registrationDTO) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(registrationDTO.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(registrationDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registrationDTO.getPassword()));
        user.setBirthDate(registrationDTO.getBirthDate());
        user.setBirthLocation(registrationDTO.getBirthLocation());
        user.setCurrentCity(registrationDTO.getCurrentCity());
        user.setGender(registrationDTO.getGender());
        user.setMoodStatus(registrationDTO.getMoodStatus());
        
        // 保存用户
        User savedUser = userRepository.save(user);
        log.info("用户注册成功: {}", savedUser.getUsername());
        
        return convertToDTO(savedUser);
    }
    
    @Override
    public UserDTO login(UserLoginDTO loginDTO) {
        // 根据用户名查找用户
        User user = userRepository.findByUsername(loginDTO.getUsername())
            .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
        
        // 验证密码
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new IllegalArgumentException("密码错误");
        }
        
        log.info("用户登录成功: {}", user.getUsername());
        return convertToDTO(user);
    }
    
    @Override
    public Optional<UserDTO> getUserById(Long id) {
        return userRepository.findById(id).map(this::convertToDTO);
    }
    
    @Override
    public Optional<UserDTO> getUserByUsername(String username) {
        return userRepository.findByUsername(username).map(this::convertToDTO);
    }
    
    @Override
    public UserDTO updateMoodStatus(Long userId, String moodStatus) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
        
        user.setMoodStatus(moodStatus);
        User updatedUser = userRepository.save(user);
        log.info("用户心情状态更新成功: {}", updatedUser.getUsername());
        
        return convertToDTO(updatedUser);
    }
    
    @Override
    public UserDTO updateCurrentCity(Long userId, String currentCity) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
        
        user.setCurrentCity(currentCity);
        User updatedUser = userRepository.save(user);
        log.info("用户当前城市更新成功: {}", updatedUser.getUsername());
        
        return convertToDTO(updatedUser);
    }
    
    @Override
    public UserDTO convertToDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setBirthDate(user.getBirthDate());
        dto.setBirthLocation(user.getBirthLocation());
        dto.setCurrentCity(user.getCurrentCity());
        dto.setGender(user.getGender());
        dto.setMoodStatus(user.getMoodStatus());
        return dto;
    }
    
    @Override
    public UserDivinationSettingsDTO getUserDivinationSettings(Long userId) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
        
        UserDivinationSettingsDTO settings = new UserDivinationSettingsDTO();
        settings.setUserId(user.getId());
        settings.setUsername(user.getUsername());
        settings.setBirthLocation(user.getBirthLocation());
        settings.setCurrentCity(user.getCurrentCity());
        settings.setGender(user.getGender());
        settings.setMoodStatus(user.getMoodStatus());
        
        // 默认设置
        settings.setUseRealSolarTime(true);
        settings.setApplyFeedback(true);
        settings.setPriorityFactor(null);
        
        // 统计信息
        if (feedbackRepository != null) {
            // 获取用户的占卜总数
            long totalDivinations = feedbackRepository.countByUserId(userId);
            settings.setTotalDivinations((int) totalDivinations);
            
            // 获取用户的准确率
            Double accuracyRate = feedbackRepository.calculateUserAccuracyRate(userId);
            if (accuracyRate != null) {
                settings.setAccuracyRate(accuracyRate);
            }
        }
        
        return settings;
    }
    
    @Override
    public UserDivinationSettingsDTO updateUserDivinationSettings(Long userId, UserDivinationSettingsDTO settings) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
        
        // 更新用户信息
        if (settings.getCurrentCity() != null) {
            user.setCurrentCity(settings.getCurrentCity());
        }
        
        if (settings.getMoodStatus() != null) {
            user.setMoodStatus(settings.getMoodStatus());
        }
        
        // 保存用户
        userRepository.save(user);
        
        // 返回更新后的设置
        return getUserDivinationSettings(userId);
    }
}